﻿//using System;
//using System.Collections.Generic;
//using System.Diagnostics;
//using System.Linq;
//using System.Net;
//using System.Text;
//using System.Threading;
//using System.Windows.Forms;
//using Awesomium.Core;
//using PMC.Scripts;
//using PMC.Structs;
//using PMC.Urls;
//using WebKit;
//using PMC.Interfaces;
//using Awesomium.Windows.Forms;
//using HtmlDocument = HtmlAgilityPack.HtmlDocument;
//using Timer = System.Windows.Forms.Timer;

//namespace PMC
//{
//    public class WbrowserChrome : WebControl, IWbrowser
//    {
//        private UriCollector uriCollector;
//        private RequestInterception requestInterception;
//        private readonly Timer urlTimer = new Timer();

//        private int timerInterval = 10000;
//        public int TimerInterval
//        {
//            get { return timerInterval; }
//            set { timerInterval = value; }
//        }

//        public DateTime TimerElapse { get; private set; }

//        public Website CurrentWebsite { get; private set; }

//        private BrowserState state = BrowserState.Stopped;
//        public BrowserState State
//        {
//            get { return state; }
//            private set { state = value; OnBrowserStateChanged(); }
//        }

//        public HtmlDocument Document
//        {
//            get
//            {
//                HtmlDocument doc = new HtmlDocument();
//                doc.LoadHtml(DocumentText);
//                return doc;
//            }
//        }
        
//        public string DocumentText
//        {
//            get { return "<html>" + ExecuteJavascriptWithResult("document.getElementsByTagName('html')[0].innerHTML").ToString() + "</html>"; }
//        }

//        public Uri Url
//        {
//            get { return Source; }
//        }

//        //private const string startPage = "about:blank";
//        public WbrowserChrome(UriCollector collector)
//        {
//            Initiate();
//            //Source = new Uri(startPage);
//            uriCollector = collector;
//            //DomReady += WbrowserChrome_LoadCompleted; //TODO rename
//            LoadCompleted += WbrowserChrome_LoadCompleted;
//            ResourceRequest += WbrowserChrome_ResourceRequest;
//            BeginLoading += new BeginLoadingEventHandler(WbrowserChrome_BeginLoading);
//            PageContentsReceived += new PageContentsReceivedEventHandler(WbrowserChrome_PageContentsReceived);
//            DomReady += new EventHandler(WbrowserChrome_DomReady);

//            urlTimer.Tick += urlTimer_Tick;
//            urlTimer.Interval = timerInterval;
//        }

//        void WbrowserChrome_DomReady(object sender, EventArgs e)
//        {
//            ExecuteJavascript("if (window.frames.length > 0) document.location.href = document.getElementsByTagName('frame')[0].src.replace('&amp;', '');");
//        }

//        void WbrowserChrome_PageContentsReceived(object sender, GetPageContentsEventArgs e)
//        {
//        }

//        void WbrowserChrome_BeginLoading(object sender, BeginLoadingEventArgs e)
//        {
//        }

//        void urlTimer_Tick(object sender, EventArgs e)
//        {
//            urlTimer.Stop();
//            if (!IsDisposed && IsRendering)
//                base.Stop();
//            Next();
//        }

//        /// <summary>
//        /// Event for intercepting requests
//        /// </summary>
//        /// <param name="sender"></param>
//        /// <param name="e"></param>
//        /// <returns></returns>
//        ResourceResponse WbrowserChrome_ResourceRequest(object sender, ResourceRequestEventArgs e)
//        {
//            if (requestInterception != null)
//            {
//                e.Request.Method = requestInterception.Method;
//                e.Request.AppendUploadBytes(requestInterception.UploadBytes);
//                e.Request.AppendExtraHeader("Content-Type", requestInterception.ContentType);

//                // Empties interception
//                requestInterception = null;
//            }

//            // We return null because we want this request to be sent to the
//            // server, we do not want to override the response.
//            return null;
//        }

//        void WbrowserChrome_LoadCompleted(object sender, EventArgs e)
//        {
//            if(!IsDomReady)
//                return;

//            Log.Instance.AddMessage("Navigated: " + Source);

//            CurrentWebsite = Website.WebsiteByUrl(Url);
//            var currentScript = CurrentWebsite == null ? Script.Default : CurrentWebsite.Script;
//            var handle = currentScript.Handle(this);
//            switch (handle.Handler)
//            {
//                case DocumentHandler.Wait:
//                    TimerInterval = currentScript.Interval;
//                    urlTimer.Start();
//                    break;
//                case DocumentHandler.Skip:
//                    Next();
//                    break;
//                case DocumentHandler.Reload:
//                    Reload();
//                    break;
//                case DocumentHandler.Replace:
//                    LoadURL(Convert.ToString(handle.Argument0));
//                    break;
//                case DocumentHandler.Post:
//                    // Todo: use content header given in argument1
//                    requestInterception = new RequestInterception { UploadBytes = Convert.ToString(handle.Argument0) };
//                    LoadURL(Convert.ToString(Source));
//                    break;
//                case DocumentHandler.NoAction:
//                    break;
//            }
//            TimerElapse = DateTime.Now;   
//            OnWebpageVisited();
//        }

//        public void Next()
//        {
//            if (IsLoadingPage)
//                return;

//            if (uriCollector.Count > 0)
//            {
//                var url = uriCollector.Next();
//                if (Source == null)
//                    Source = url;
//                else
//                    LoadURL(url.ToString());
//            }
//            else
//            {
//                Stop();
//            }
//        }

//        public new void Stop()
//        {
//            Log.Instance.AddMessage("Webbrowser [" + GetHashCode() + "] deactivated");
//            State = BrowserState.Stopped;
//            urlTimer.Stop();
//            //UrlList.UrlAdded += UrlList_UrlAdded;
//        }

//        public void Start()
//        {
//            Log.Instance.AddMessage("Webbrowser [" + GetHashCode() + "] activated");
//            State = BrowserState.Started;
//            Next();
//        }

//        public void Navigate(Uri url)
//        {
//            LoadURL(url.ToString());
//        }

//        public void SetCookie(Uri url, CookieCollection cookie)
//        {
//            foreach (var cook in cookie)
//            {
//                // Set cookie via internal function
//                WebCore.SetCookie(url.ToString(), cook +"; expires=" + DateTime.Now.AddMonths(1).ToString("r") + "; path=/", false, false);
//                // Set cookie via JavaScript injection (just to make sure)
//                ExecuteJavascript("document.cookie = '" + cook + "; expires=" + DateTime.Now.AddMonths(1).ToString("r") + "; path=/'");
//            }
//        }

//        public CookieCollection GetCookies(Uri url)
//        {
//            var cookies = WebCore.GetCookies(url.ToString(), false);
//            return Global.HtmlUtility.CookieHeaderToCookieCollection(cookies, url);
//        }

//        public CookieCollection GetCookies()
//        {
//            return GetCookies(Source);
//        }

//        public event webpageChanged WebpageVisited;
//        public void OnWebpageVisited()
//        {
//            if (WebpageVisited != null)
//            {
//                WebpageVisited(CurrentWebsite, Url);
//            }
//        }

//        public event browserStateChanged BrowserStateChanged;
//        public void OnBrowserStateChanged()
//        {
//            if (BrowserStateChanged != null)
//            {
//                BrowserStateChanged(state);
//            }
//        }

//        /// <summary>
//        /// Initiate webconfig
//        /// </summary>
//        private static void Initiate()
//        {
//            if (WebCore.IsRunning)
//                return;

//            if (WebCore.IsChildProcess)
//            {
//                WebCore.ChildProcessMain();

//                // When our process is not used any more, exit it.
//                return;
//            }

//            WebCoreConfig config = new WebCoreConfig
//            {
//                SaveCacheAndCookies = true,
//                //EnableVisualStyles = false,
//                //EnablePlugins = false,
//                //LogLevel = LogLevel.Verbose
//            };
//            //if (!Process.GetCurrentProcess().ProcessName.EndsWith("vshost"))
//            //{
//            //    // We demonstrate using our own executable as child rendering process.
//            //    // Also see the entry point (Main function) in Program.cs.
//            //    config.ChildProcessPath = WebCoreConfig.CHILD_PROCESS_SELF;
//            //}

//            WebCore.Initialize(config);
//        }

//        //protected override void Dispose(bool disposing)
//        //{
//        //    WebCore.Shutdown();
//        //    base.Dispose(disposing);
//        //}
//    }

//    public class RequestInterception
//    {
//        private string method = "POST";
//        public string Method
//        {
//            get { return method; }
//            set { method = value; }
//        }

//        public string UploadBytes { get; set; }
//        private string contentType = "application/x-www-form-urlencoded";
//        public string ContentType
//        {
//            get { return contentType; }
//            set { contentType = value; }
//        }
//    }
//}
